<template>
  <div>
    <el-table height="60vh" :data="dorm" style="width: 100%">
      <el-table-column prop="address" label="宿舍地址" />
      <el-table-column prop="number" label="可住/已住">
        <template slot-scope="scope">
          <span v-if="scope.row.number > getResided(scope.row.room)" style="color: #67c23a">{{ scope.row.number }}/{{
            getResided(scope.row.room) }}</span>
          <span v-else style="color: #f56c6c">{{ scope.row.number }}/{{ getResided(scope.row.room) }}</span>
          <el-popover placement="bottom" title="房间" width="200" trigger="click">
            <div class="">
              <div v-for="(item, key) in scope.row.room" :key="key" style="margin-bottom: 5px">
                <span> {{ item.name }}: </span>
                <span v-for="(items, keys) in item.userCompany" :key="keys" style="
                      margin-right: 2px;
                      cursor: pointer;
                      background-color: #f1f1f1;
                      padding: 5px;
                      border-radius: 5px;
                    " @click="toShow(items.user)">
                  {{ items?.user?.username }}
                </span>
              </div>
            </div>
            <el-button slot="reference" type="text"><i class="el-icon-view" /></el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="rent" label="租金" />
      <el-table-column prop="photo" label="照片">
        <template slot-scope="scope">
          <el-image v-if="arrImg(scope.row)" :src="arrImg(scope.row, true)"
            :preview-src-list="arrImg(scope.row, false)" />
          <el-button v-else type="text">未上传</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="number">
        <template slot="header">
          <el-button type="text" @click="add()">操作</el-button>
        </template>
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <el-button type="text" @click="check(scope.row)">选择</el-button>
            <el-dropdown-menu slot="dropdown" v-if="scope.row.room.length > 0">
              <el-dropdown-item v-for="(item, key) in withCapacity(scope.row.room)" :key="key" :disabled="item.disabled"
                @click.native="chooseRoomWithConfirm(item,scope.row)">{{ item.name
                }}<span style="margin-left: 10px">还可住:{{ item.spare_bed }}</span></el-dropdown-item>
            </el-dropdown-menu>
            <el-dropdown-menu slot="dropdown" v-else>
              <el-dropdown-item @click.native="createRoom(scope.row)">暂无配置房间,前去创建</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { userRoom } from "@/api/personnel";
import { getDormitory } from "@/api/basic";
import { delDorm } from "@/api/dorm";
import { isArray, isNumber } from "@/utils/kris_utils";
export default {
  props: {
    checks: {
      default: true,
    },
    userId: {
      type: String,
    },
  },
  data() {
    return {
      dorm: [],
      dormitory: {
        user_id: "",
        room_id: "",
      },
      fileList: [],
      dormDialogVisible: false,
      roomName: "",
      baseUrl: "",
      type: "create",
      rules: {
        address: [
          {
            required: true,
            message: "请输入地址",
            trigger: ["blur", "change"],
          },
        ],
        rent: [
          {
            required: true,
            message: "请输入租金",
            trigger: ["blur", "change"],
          },
        ],
        number: [
          {
            required: true,
            message: "请输入可住人数",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    this.baseUrl = process.env.VUE_APP_UPLOAD;
  },
  mounted() {
    this.getDormitorys();
  },
  methods: {
    createRoom(data) {
      this.$router.push(`/dormitory/show/${data.id}`);
    },
    // 获取当前房间以住人数
    getResided(arr) {
      let count = 0
      arr.map(item => {
        count += item.userCompany.length
      })
      return count
    },
    withCapacity(room) {
      if (!isArray(room))
        return room
      return room.map(item => {
        const { number, userCompany } = item
        if (!isNumber(number) || !isArray(userCompany)) {
          item['disabled'] = false
          return item
        }

        item['disabled'] = userCompany.length >= number
        return item
      })
    },
    chooseRoomWithConfirm(data,apartment) {
      this.$confirm('是否选择该宿舍？', '提示')
        .then(() => {
          data['dormitory'] = apartment
          this.room(data)
        })
    },
    async room(data) {
      if (data.spare_bed == 0) {
        return this.$message.error("该房间暂无可住位置，请选择其他房间");
      }
      this.dormitory.user_id = this.userId;
      this.dormitory.room_id = data.id;
      if (this.dormitory.user_id) {
        const res = await userRoom(this.dormitory);
        this.$message({
          message: "更改成功",
          type: "success",
        });
        this.$emit("closeMain", data);
        this.edit = false;
        console.log(res);
      } else {
        this.$emit("closeMain", data);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      }
      return isJPG || (isPNG && isLt2M);
    },
    arrImg(str, value) {
      const photo = str.photo ? JSON.parse(str.photo) : [];
      if (photo.length > 0) {
        if (value) {
          return photo[0];
        } else {
          return photo;
        }
      } else {
        return false;
      }
    },
    async getDormitorys() {
      const res = await getDormitory();
      console.log(res.data, 999999);
      this.dorm = res.data;
    },
    check(data) {
      if (Object.prototype.toString.call(data) !== '[object Object]')
        return

      if (data.room_count <= 0) {
        this.$message.error('该宿舍暂无房间')
        return
      }

      this.$emit("change", data);
    },
    handle_remove(file, fileList) {
      const index = this.dormForm.photo.findIndex(
        (item) => item.uid === file.uid
      );
      index !== -1 && this.dormForm.photo.splice(index, 1);
    },

    handle_success(response, file, fileList) {
      this.dormForm.photo.push({
        name: file.name,
        url: file.response.data.path,
      });
    },
    toShow(data) {
      this.$router.push({
        path: `/personnel-files/show/${data.id}`,
        query: {
          tag_title: data.username + "-查看",
        },
      });
    },
    clear() {
      this.$refs.upload.clearFiles();
      this.dormDialogVisible = false;
    },
    add() {
      this.dormForm = this.$options.data().dormForm;
      this.$nextTick(() => {
        this.$refs?.form?.clearValidate();
      });
      this.type = "create";
      this.dormDialogVisible = true;
    },
    del(data) {
      this.$confirm("此操作将删除该部门, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delDorm({
          id: `[${data.id}]`,
        }).then((res) => {
          if (res.code == 201) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getDormitorys();
          } else {
            this.$message({
              message: "当前宿宿舍下还有员工，请转移后再删除",
              type: "warning",
            });
          }
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
:deep(.el-image) {
  width: 100px !important;
  height: 100px !important;
}

.personnel {
  display: flex;
}
</style>
